<template>
  <div>
    <el-row type="fixed">
      <el-col
        span="3"
      >
        <el-button type="primary" size="small" icon="el-icon-plus" @click="showAddDialog">新增</el-button>
      </el-col>
      <el-col
        span="21"
      >
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="搜索">
            <el-input v-model="params.search" placeholder="Search" size="small" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-search" @click="onSubmit">查询</el-button>
            <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-card class="cardTable">
      <el-table
        ref="multipleTable"
        stripe
        border
        height="75vh"
        :header-cell-style="{background:'#eef1f6',color:'#606266' }"
        :data="tableData"
        :row-style="{height: '0px'}"
        :cell-style="{padding: '0px'}"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        :default-sort = "{prop: 'date', order: 'descending'}"
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          v-for="(item, index) in tableKeys"
          :key="index"
          :prop="item[0]"
          :label="item[1]"
          sortable
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="editProduct(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" @click="deleteProduct(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-row align="middle" type="flex" justify="center">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[14, 20, 30, 40]"
        :page-size="params.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>
    <!-- 新增弹窗 -->
    <el-dialog
      :title="dialogTitle"
      width="32vw"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="productForm"
        :model="formAddProduct"
        label-width="80px"
        class="dialog-form"
        :rules="rules"
      >
        <el-card style="width: 20vw" shadow="hover">
          <el-form-item label="商品ID" label-width="80px" prop="goods_id">
            <el-input v-model="formAddProduct.goods_id" />
          </el-form-item>
          <el-form-item label="商品名称" label-width="80px" prop="name">
            <el-input v-model="formAddProduct.name" />
          </el-form-item>
          <el-form-item label="商品编码" label-width="80px" prop="code">
            <el-input v-model="formAddProduct.code" />
          </el-form-item>
          <el-form-item label="商品颜色" label-width="80px" prop="color">
            <el-input v-model="formAddProduct.color" />
          </el-form-item>
          <el-form-item label="商品分类" label-width="80px" prop="category">
            <el-select v-model="formAddProduct.category" placeholder="请选择分类">
              <el-option
                v-for="item in $store.state.basic_data.categories"
                :key="item.id"
                :label="item.category_name"
                :value="item.id"
              />
              <div class="select-button">
                <el-button type="text" icon="el-icon-plus" @click="inDialogVisible=true">新增分类</el-button>
              </div>
            </el-select>
          </el-form-item>
          <el-form-item label="单位" label-width="80px" prop="unit">
            <el-select v-model="formAddProduct.unit" placeholder="请选择单位">
              <el-option
                v-for="item in $store.state.basic_data.units"
                :key="item.id"
                :label="item.unit_name"
                :value="item.id"
              />
              <div class="select-button">
                <el-button type="text" icon="el-icon-plus" @click="unitsDialogVisible=true">新增单位</el-button>
              </div>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" label-width="80px" prop="supplier">
            <el-select v-model="formAddProduct.supplier" placeholder="请选择供应商">
              <el-option
                v-for="item in $store.state.basic_data.suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
              <div class="select-button">
                <el-button type="text" icon="el-icon-plus" @click="supplierDialogVisible=true">新增供应商</el-button>
              </div>
            </el-select>
          </el-form-item>
        </el-card>
      </el-form>
      <!--      内置弹窗-->
      <el-dialog
        ref="categoryForm"
        title="新增分类"
        :model="formAddCategory"
        :rules="rules"
        :visible.sync="inDialogVisible"
        width="30%"
        append-to-body
      >
        <el-form>
          <el-form-item label="分类名称" label-width="80px" prop="category_name">
            <el-input v-model="formAddCategory.category_name" />
          </el-form-item>
          <el-form-item label="分类编码" label-width="80px" prop="category_code">
            <el-input v-model="formAddCategory.code" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="inHandleCancel">取 消</el-button>
          <el-button type="primary" @click="handleCategory">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        ref="categoryForm"
        title="新增单位"
        :model="formAddUnit"
        :rules="rules"
        :visible.sync="unitsDialogVisible"
        width="30%"
        append-to-body
      >
        <el-form>
          <el-form-item label="单位名称" label-width="80px" prop="category_name">
            <el-input v-model="formAddUnit.unit_name" />
          </el-form-item>
          <el-form-item label="单位编码" label-width="80px" prop="category_code">
            <el-input v-model="formAddUnit.code" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="unitsHandleCancel">取 消</el-button>
          <el-button type="primary" @click="handleUnit">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        ref="categoryForm"
        title="新增供应商"
        :model="formAddSupplier"
        :rules="rules"
        :visible.sync="supplierDialogVisible"
        width="30%"
        append-to-body
      >
        <el-form>
          <el-form-item label="供应商名称" label-width="100px" prop="category_name">
            <el-input v-model="formAddSupplier.name" />
          </el-form-item>
          <el-form-item label="供应商编码" label-width="100px" prop="category_code">
            <el-input v-model="formAddSupplier.code" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="supplierHandleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSupplier">确 定</el-button>
        </div>
      </el-dialog>
      <!--      内置弹窗结束-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleProduct">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增弹窗结束 -->
  </div>
</template>

<script>
import { GoodsAPI, GoodsCreateAPI, GoodsDeleteAPI, GoodsUpdateAPI } from '@/api/BasicData/goods'
import { createSuppliers, getSuppliers } from '@/api/BasicData/suppliers'
import { createUnit, getUnits } from '@/api/BasicData/units'
import { createCategory, getCategory } from '@/api/BasicData/category'

export default {
  name: 'Products',
  data() {
    return {
      supplierDialogVisible: false,
      unitsDialogVisible: false,
      inDialogVisible: false,
      formAddProduct: {
        goods_id: '',
        name: '',
        code: '',
        color: '',
        category: '',
        unit: '',
        supplier: '',
        description: ''
      },
      formAddCategory: {
        code: '',
        category_name: ''
      },
      formAddUnit: {
        unit_name: '',
        code: ''
      },
      formAddSupplier: {
        name: '',
        code: ''
      },
      formSearch: {
        goods_id: '',
        name: '',
        code: '',
        color: '',
        category: '',
        unit: '',
        supplier: ''
      },
      tableData: [],
      tableKeys: [
        ['goods_id', '产品编号'],
        ['name', '产品名称'],
        ['create_time', '创建时间'],
        ['supplier.name', '供应商'],
        ['unit.unit_name', '单位'],
        ['code', '规格型号'],
        ['price', '单价'],
        ['color', '颜色'],
        ['category.category_name', '分类'],
        ['stock', '库存量'],
        ['defective_quantity', '次品数量']
        // ['requested_delivery_date', '要求交货日期'],
        // ['actual_delivery_date', '实际交货日期']
      ],
      params: {
        page_size: 14,
        page: 1,
        search: ''
      },
      total: 0,
      dialogFormVisible: false,
      suppliers: [],
      units: [],
      categories: [],
      rules: {
        goods_id: [
          { required: true, message: '请输入商品ID', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入商品编码', trigger: 'blur' }
        ],
        color: [
          { required: true, message: '请输入商品颜色', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        unit: [
          { required: true, message: '请选择商品单位', trigger: 'change' }
        ],
        supplier: [
          { required: true, message: '请选择商品供应商', trigger: 'change' }
        ],
        category_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        category_code: [
          { required: true, message: '请输入分类编码', trigger: 'blur' }
        ]
      },
      dialogTitle: '新增商品'
    }
  },
  async created() {
    await this.$store.dispatch('basic_data/fetchSuppliers')
    await this.$store.dispatch('basic_data/fetchUnits')
    await this.$store.dispatch('basic_data/fetchCategories')
    await this.getGoods()
  },
  methods: {
    onSubmit() {
      this.params.page = 1
      this.getGoods()
    },
    onReset() {
      this.params.page = 1
      this.params.search = ''
      this.getGoods()
    },
    inHandleCancel() {
      this.inDialogVisible = false
    },
    unitsHandleCancel() {
      this.unitsDialogVisible = false
    },
    supplierHandleCancel() {
      this.supplierDialogVisible = false
    },
    handleClick(row) {
      console.log(row)
    }, // 点击行
    async getGoods() {
      await this.$store.dispatch('basic_data/fetchProducts')
      this.total = this.$store.state.basic_data.products.length
      const data = this.$store.state.basic_data.products.slice((this.params.page - 1) * this.params.page_size, this.params.page * this.params.page_size)
      this.tableData = data.map(item => {
        return {
          ...item,
          create_time: item.create_time.slice(0, 10), // 日期格式化
          category: this.$store.state.basic_data.categories.find(item1 => item1.id === item.category),
          unit: this.$store.state.basic_data.units.find(item1 => item1.id === item.unit),
          supplier: this.$store.state.basic_data.suppliers.find(item1 => item1.id === item.supplier)
        }
      })
    }, // 获取商品列表
    handleEdit(row) {
      this.$router.push({
        name: 'EditProducts', params: { id: row.goods_id }
      })
    }, // 编辑
    handleSizeChange(val) {
      this.params.page_size = val
      this.getGoods()
    }, // 每页显示条数
    handleCurrentChange(val) {
      // this.params.search = ''
      this.params.page = val
      this.getGoods()
    }, // 当前页
    handleSelectionChange(val) {
      console.log(val)
    }, // 多选
    async showAddDialog() {
      this.dialogTitle = '新增商品'
      this.dialogFormVisible = true
      this.params.page = Math.ceil(this.total / this.params.page_size)
      const res = await GoodsAPI(this.params)
      console.log(res)
      const code = res.results[res.results.length - 1].goods_id
      const num = +code.replace(/[a-zA-Z]/g, '') + 1
      const title = code.replace(/\d+/g, '')
      this.formAddProduct.goods_id = title + num
    }, // 显示新增弹窗
    async getSupplier() {
      this.suppliers = (await getSuppliers()).results
    }, // 获取供应商
    async getUnit() {
      this.units = (await getUnits()).results
    }, // 获取单位
    async getCategory() {
      this.categories = (await getCategory()).results
    }, // 获取分类
    async handleProduct() { // 新增商品
      if (this.dialogTitle === '编辑商品') {
        this.$refs.productForm.validate(async valid => {
          if (valid) {
            const res = await GoodsUpdateAPI(this.formAddProduct)
            if (res.goods_id === this.formAddProduct.goods_id) {
              console.log('ok')
              this.$message.success('编辑成功')
              this.dialogFormVisible = false
              await this.getGoods()
              this.$refs['productForm'].resetFields()
            } else {
              this.$message.error('编辑失败，请重试')
            }
          }
        })
      } else {
        this.$refs.productForm.validate(async valid => {
          if (valid) {
            const res = await GoodsCreateAPI(this.formAddProduct)
            if (res.goods_id === this.formAddProduct.goods_id) {
              console.log('ok')
              this.$message.success('新增成功')
              this.dialogFormVisible = false
              await this.getGoods()
              this.$refs['productForm'].resetFields()
            } else {
              this.$message.error('新增失败，请重试')
            }
          } else {
            this.$message.error('请填写完整信息')
          }
        })
      }
    },
    async editProduct(row) { // 编辑商品
      this.formAddProduct = { ...row }
      this.formAddProduct.category = row.category.id
      this.formAddProduct.unit = row.unit.id
      this.formAddProduct.supplier = row.supplier.id
      this.dialogTitle = '编辑商品'
      this.dialogFormVisible = true
    },
    async deleteProduct(row) {
      const res = await GoodsDeleteAPI(row.id)
      console.log(res)
      if (!res) {
        this.$message.success('删除成功')
        await this.refreshPage()
      } else {
        this.$message.error('删除失败，请重试')
      }
    }, // 删除商品
    handleCancel() {
      this.dialogFormVisible = false
      this.formAddProduct = {
        goods_id: '',
        name: '',
        code: '',
        color: '',
        category: '',
        unit: '',
        supplier: '',
        description: ''
      }
      this.$refs['productForm'].resetFields()
    },
    refreshPage() {
      const index = this.params.page * this.params.pageSize
      this.tableData.splice(index, 1)
      this.totalPage = Math.ceil(this.tableData.length / this.params.pageSize)
      if (this.this.params.page === this.totalPage && this.tableData.length < this.params.pageSize) {
        this.currentPage--
      }
      this.getGoods()
    },
    async handleCategory() {
      const res = await createCategory(this.formAddCategory)
      if (res) {
        this.$message.success('新增成功')
        this.inDialogVisible = false
        this.formAddCategory.category_name = ''
        this.formAddCategory.code = ''
        await this.$store.dispatch('basic_data/fetchCategories')
      } else if (res.code === 400) {
        this.$message.error('新增失败，请重试')
      } else {
        this.$message.error('请填写完整信息')
      }
    },
    async handleUnit() {
      const res = await createUnit(this.formAddUnit)
      if (res) {
        this.$message.success('新增成功')
        this.unitsDialogVisible = false
        this.formAddUnit.unit_name = ''
        this.formAddUnit.code = ''
        await this.$store.dispatch('basic_data/fetchUnits')
      } else if (res.code === 400) {
        this.$message.error('新增失败，请重试')
      } else {
        this.$message.error('请填写完整信息')
      }
    },
    async handleSupplier() {
      const res = await createSuppliers(this.formAddSupplier)
      if (res) {
        this.$message.success('新增成功')
        this.supplierDialogVisible = false
        this.formAddSupplier.name = ''
        this.formAddSupplier.code = ''
        await this.$store.dispatch('basic_data/fetchSuppliers')
      } else if (res.code === 400) {
        this.$message.error('新增失败，请重试')
      } else {
        this.$message.error('请填写完整信息')
      }
    } // 新增供应商
  } // 新增分类
}

</script>

<style lang="scss" scoped>
.el-card {
  margin-bottom: 20px;
}

.cardTable {
  height: 78%;
}

.dialog-form {
  display: flex;
  justify-content: center;
  align-items: center;
}

.select-button {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}
</style>
